<template>
  <CollapseContainer
    :title="t('routes.dashboard.account.setting.baseSetting.title')"
    :canExpand="false"
  >
    <a-row :gutter="24">
      <a-col :span="16">
        <BasicForm @register="register" :compact="true">
          <template #tagSlot="{ model, field }">
            <TagEditor
              :value="model[field]"
              :omitLength="15"
              :addTagText="t('routes.dashboard.account.setting.baseSetting.addTag')"
              :randomColor="true"
              @change="handleTagChange"
            />
          </template>
        </BasicForm>
      </a-col>
      <a-col :span="8">
        <div class="change-avatar">
          <!-- <div class="mb-2"> {{ t('routes.dashboard.account.setting.baseSetting.avatar') }} </div> -->
          <img width="140" :src="userInfo.Avatar || uploadAvatarImg" />
          <Upload :showUploadList="false" :accept="avatarFormat" :beforeUpload="handleUploadAvatar">
            <Button>
              <Icon icon="feather:upload" />{{
                t('routes.dashboard.account.setting.baseSetting.changeAvatar')
              }}
            </Button>
          </Upload>
        </div>
        <div class="change-avatar" t>
          <!-- <div class="mb-2">
            {{ t('routes.dashboard.account.setting.baseSetting.signature') }}
          </div> -->
          <img width="230" :src="userInfo.Signature || signatureImg" />
          <Upload
            :showUploadList="false"
            :accept="signatureFormat"
            :beforeUpload="handleUploadSignature"
          >
            <Button>
              <Icon icon="feather:upload" />
              {{ t('routes.dashboard.account.setting.baseSetting.uploadSignature') }}
            </Button>
          </Upload>
        </div>
      </a-col>
    </a-row>
    <Authority :value="'Root.Identity.ProfileEdit'">
      <Button type="primary" @click="handleSubmit">
        {{ t('routes.dashboard.account.setting.baseSetting.btnSubmitTitle') }}
      </Button>
    </Authority>
  </CollapseContainer>
</template>
<script lang="ts" setup>
  import { Button, Upload, Row, Col } from 'ant-design-vue';
  import { onMounted, ref } from 'vue';
  import { BasicForm, useForm } from '@/components/Form/index';
  import { CollapseContainer } from '@/components/Container/index';
  import Icon from '@/components/Icon/Icon.vue';
  import { useI18n } from '@/hooks/web/useI18n';
  import { TagEditor } from '@/components/Tag';
  import { useLoading } from '@/components/Loading';
  import { Authority } from '@/components/Authority';

  import uploadAvatarImg from '@/assets/images/user_focus.png';
  import signatureImg from '@/assets/images/signature_solid.png';

  import { useMessage } from '@/hooks/web/useMessage';

  import { baseSetschemas } from './data';
  import { useIdentityStore } from '@/store/modules/identity';
  import { UserInfo } from '@/api/identity/model';
  import { getBase64 } from '@/utils/common';

  const ARow = Row;
  const ACol = Col;

  const { createMessage } = useMessage();
  const [openLoading, closeLoading] = useLoading({});
  const identityStore = useIdentityStore();
  const { t } = useI18n();
  const userInfo = ref(identityStore.getUserInfo);
  const avatarFormat = '.jpg,.jpeg,.png,.bmp,.ico,.gif';
  const signatureFormat = '.jpg,.jpeg,.png,.bmp';

  const [register, { setFieldsValue, validate }] = useForm({
    labelWidth: 160,
    schemas: baseSetschemas,
    showActionButtonGroup: false,
  });

  onMounted(async () => {
    userInfo.value = identityStore.getUserInfo;
    setFieldsValue(userInfo.value);
  });

  /** 处理上传头像 */
  const handleUploadAvatar = (file: File) => {
    try {
      openLoading();

      const isJpgOrPng =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/bmp' ||
        file.type === 'image/gif' ||
        file.type === 'image/x-icon';
      if (!isJpgOrPng) {
        createMessage.error(t('component.upload.acceptUpload', [avatarFormat]));
        return isJpgOrPng;
      }
      const isLt1M = file.size / 1024 / 1024 < 1;
      if (!isLt1M) {
        createMessage.error(t('component.upload.maxSize', '1'));
        return isLt1M;
      }
      getBase64(file, (base64Url: string) => {
        identityStore
          .profileEdit({
            Id: userInfo.value.UserId,
            UserName: userInfo.value.UserName,
            NickName: userInfo.value.NickName,
            Email: userInfo.value.Email,
            PhoneNumber: userInfo.value.PhoneNumber,

            Avatar: base64Url,
            Signature: userInfo.value.Signature,

            Gender: userInfo.value.Gender,
            Birthday: userInfo.value.Birthday,
            BloodType: userInfo.value.BloodType,
            Tag: userInfo.value.Tag,
            Title: userInfo.value.Title,
            Address: userInfo.value.Address,
            Profile: userInfo.value.Profile,
            Sign: userInfo.value.Sign,
            Remark: userInfo.value.Remark,

            HomePath: userInfo.value.HomePath,
          })
          .then((res) => {
            if (res !== undefined && res !== null) {
              userInfo.value = res as UserInfo;
              createMessage.success(t('routes.dashboard.account.setting.submitSuccess'));
            }
          });
      });
    } finally {
      closeLoading();
    }
    return false;
  };
  /** 处理上传签名 */
  const handleUploadSignature = (file: File) => {
    try {
      openLoading();

      const isJpgOrPng =
        file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/bmp';
      if (!isJpgOrPng) {
        createMessage.error(t('component.upload.acceptUpload', [signatureFormat]));
        return isJpgOrPng;
      }
      const isLt1M = file.size / 1024 / 1024 < 1;
      if (!isLt1M) {
        createMessage.error(t('component.upload.maxSize', '1'));
        return isLt1M;
      }
      getBase64(file, (base64Url: string) => {
        identityStore
          .profileEdit({
            Id: userInfo.value.UserId,
            UserName: userInfo.value.UserName,
            NickName: userInfo.value.NickName,
            Email: userInfo.value.Email,
            PhoneNumber: userInfo.value.PhoneNumber,

            Avatar: userInfo.value.Avatar,
            Signature: base64Url,

            Gender: userInfo.value.Gender,
            Birthday: userInfo.value.Birthday,
            BloodType: userInfo.value.BloodType,
            Tag: userInfo.value.Tag,
            Title: userInfo.value.Title,
            Address: userInfo.value.Address,
            Profile: userInfo.value.Profile,
            Sign: userInfo.value.Sign,
            Remark: userInfo.value.Remark,

            HomePath: userInfo.value.HomePath,
          })
          .then((res) => {
            if (res !== undefined && res !== null) {
              userInfo.value = res as UserInfo;
              createMessage.success(t('routes.dashboard.account.setting.submitSuccess'));
            }
          });
      });
    } finally {
      closeLoading();
    }
    return false;
  };

  /** 处理用户标签变更 */
  function handleTagChange(tags: string[]) {
    // console.log(tags);
    setFieldsValue({ Tag: tags });
  }

  /** 处理提交 */
  async function handleSubmit() {
    const data = await validate();
    if (!data) return;
    try {
      openLoading();

      userInfo.value = (await identityStore.profileEdit({
        Id: userInfo.value.UserId,
        UserName: data.UserName,
        NickName: data.NickName,
        Email: data.Email,
        PhoneNumber: data.PhoneNumber,

        Avatar: userInfo.value.Avatar,
        Signature: userInfo.value.Signature,

        Gender: data.Gender,
        Birthday: data.Birthday,
        BloodType: data.BloodType,
        Tag: data.Tag,
        Title: data.Title,
        Address: data.Address,
        Profile: data.Profile,
        Sign: data.Sign,
        Remark: data.Remark,

        HomePath: data.HomePath,
      })) as UserInfo;
      if (userInfo.value) {
        createMessage.success(t('routes.dashboard.account.setting.submitSuccess'));
      }
    } finally {
      closeLoading();
    }
  }
</script>

<style lang="less" scoped>
  .change-avatar {
    margin: 0 auto;
    margin-bottom: 15px;
    text-align: center;

    img {
      display: block;
      margin: 0 auto;
      margin-bottom: 15px;
      text-align: center;
      // border-radius: 50%;
    }
  }
</style>
